package com.demo.wordex.controller;

import com.demo.wordex.model.UserInfo;
import com.demo.wordex.utils.WordUtil;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 秋牧
 * 2024/7/22 16:49
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private WordUtil wordUtil;

    /**
     * 基于模板生成 Word 文档
     *
     * @param response response
     */
    @GetMapping("/generate_word")
    public void generateWord(HttpServletResponse response) {
        Map<String, String> templateParam = new HashMap<>(5);
        templateParam.put("name", "小明");
        templateParam.put("sex", "男");
        templateParam.put("age", "18");
        templateParam.put("birthday", "2024-07-22");
        templateParam.put("cardNum", "440000000000001111");

        try {
            // 设置 HTTP 响应的内容类型为 Microsoft Word 文档
            response.setContentType("application/msword");
            // 设置响应字符编码为 UTF-8
            response.setCharacterEncoding("utf-8");
            // 使用 URLEncoder 对文件名进行编码，以防止中文文件名在不同浏览器和操作系统下出现乱码问题
            String filename = URLEncoder.encode("测试Word_" + System.currentTimeMillis(), "utf-8");
            // 设置响应头，指定文档将以附件的形式下载，并定义文件名
            response.setHeader("Content-disposition", "attachment;filename=" + filename + ".doc");
            // 创建 Freemarker 的 Configuration 对象，设置默认的不兼容改进选项
            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            configuration.setDefaultEncoding("utf-8");
            // 设置模板加载器，加载模板文件
            configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/templates"));
            Template t = configuration.getTemplate("generate_word_test.xml", "utf-8");
            // 创建 Writer 对象，用于将生成的文档写到输出流中，缓存区大小设为 10KB
            Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8), 10240);
            // 将模型数据与模板结合生成 Word 文档，写入到 Writer 对象中
            t.process(templateParam, out);
            out.close();
        } catch (Exception e) {
            log.info("生成Word文档异常，异常原因：{}", e.getMessage(), e);
            throw new RuntimeException("生成Word文档异常，异常原因：" + e.getMessage());
        }
    }

    /**
     * 基于模板生成 Word 文档（基于示例 1 提取 Word 工具类）
     *
     * @param response response
     */
    @GetMapping("/generate_word_2")
    public void generateWord2(HttpServletResponse response) {
        Map<String, String> templateParam = new HashMap<>(5);
        templateParam.put("name", "小明");
        templateParam.put("sex", "男");
        templateParam.put("age", "18");
        templateParam.put("birthday", "2024-07-22");
        templateParam.put("cardNum", "440000000000001111");

        wordUtil.generate(response, "/templates", "generate_word_test.xml", templateParam, "测试Word");
    }

    /**
     * 基于模板生成 Word 文档（使用对象入参）
     *
     * @param response response
     */
    @GetMapping("/generate_word_3")
    public void generateWord3(HttpServletResponse response) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName("小明");
        userInfo.setSex("男");
        userInfo.setAge("18");
        userInfo.setBirthday("2024-07-22");
        userInfo.setCardNum("440000000000001111");

        wordUtil.generate(response, "/templates", "generate_word_test.xml", userInfo, "测试Word");
    }

    /**
     * 基于模板生成 Word 文档（生成动态列表）
     *
     * @param response response
     */
    @GetMapping("/generate_dynamic_word")
    public void generateDynamicWord(HttpServletResponse response) {
        List<UserInfo> userList = new ArrayList<>();
        userList.add(new UserInfo("小明", "男", "18", "2024-07-22", "440000000000001111"));
        userList.add(new UserInfo("小红", "女", "20", "2024-07-26", "440000000000002222"));
        userList.add(new UserInfo("小白", "男", "17", "2024-07-24", "440000000000003333"));
        userList.add(new UserInfo("小蓝", "女", "19", "2024-07-23", "440000000000004444"));
        userList.add(new UserInfo("小黑", "男", "18", "2024-07-21", "440000000000005555"));
        Map<String, Object> templateParam = new HashMap<>(5);
        templateParam.put("date", LocalDate.now());
        templateParam.put("total", userList.size());
        templateParam.put("userList", userList);

        wordUtil.generate(response, "/templates", "dynamic_userlist.xml", templateParam, "测试动态列表Word");
    }

}
